package com.sk.weichat.util;

import android.app.Activity;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorRes;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.sk.weichat.R;
import com.sk.weichat.ui.base.CoreManager;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Call;

import static com.sk.weichat.ui.message.ChatBackgroundActivity.event_change_chat_bg;

/**
 * @author lzs
 * @date 2019/9/17
 * Email:343067508@qq.com
 **/
public class ChangeBackgroundHelper {
    //全局默认ChatID;
    public final static String DefaultChatID = "DefaultChatID";

    private final static String perfix = "isUse";


    private static final Map<String, Observer<String>> cache = new HashMap<>();

    public static void registOnBackgroundChangeListener(Context context, OnBackgroundChangeListener activity, String id) {

        String filePath = PreferenceUtils.getString(context, id);
        Log.e("lzs", "filePath:" + filePath);
        if (!TextUtils.isEmpty(filePath)) {
            File file = new File(filePath);
            if (file.exists()) {
                loadImage(context, activity, id, file);
            }
        }
        if (filePath == null) {
            //没有单独设置背景图，检查是否设置全局背景tu
            String filePathDefault = PreferenceUtils.getString(context, DefaultChatID);
            if (!TextUtils.isEmpty(filePathDefault)) {
                //设置有全局背景图
                File file = new File(filePathDefault);
                if (file.exists()) {
                    loadImage(context, activity, DefaultChatID, file);
                }
            }
        }
        Observer<String> observer = new Observer<String>() {

            @Override
            public void onChanged(@Nullable String s) {
                Log.e("lzs", "onChanged  s:" + s + "  id:" + id);
                if (TextUtils.isEmpty(s)) {
                    if (activity != null) {
                        PreferenceUtils.putString(context, id, "");
                        activity.handle(true, null);
                    }
                } else {
                    //
                    File file = new File(s);
                    if (file.exists()) {
                        loadImage(context, activity, id, file);
                    }
                }

            }
        };
        cache.put(id, observer);
        LiveDataBus.get().with(event_change_chat_bg, String.class).observeForever(observer);
    }

    /**
     * 是否设置了背景图
     *
     * @param id
     */
    public static final boolean isSetBackground(Context context, String id) {
        if (PreferenceUtils.getString(context, id) == null) {
            return !TextUtils.isEmpty(PreferenceUtils.getString(context, DefaultChatID));
        } else if(PreferenceUtils.getString(context, id).equals("")){
            return false;
        }else{
            return true;
        }
    }

    public static final void unRegistOnBackgroundChangeListener(String chatID) {
        Observer<String> observer = cache.get(chatID);
        if (observer != null) {
            LiveDataBus.get().with(event_change_chat_bg, String.class).removeObserver(observer);
        }
    }

    /**
     * sharepreference查找对应聊天的背景图的id
     *
     * @param chatID
     * @return
     */
    public static String getBackgroundIDByChatID(Context context, String chatID) {
        if (TextUtils.isEmpty(chatID)) {
            return null;
        } else {
            String filePath = PreferenceUtils.getString(context, chatID);
            if (!TextUtils.isEmpty(filePath)) {
                return filePath.substring(filePath.lastIndexOf("/") + 1);
            } else {
                return null;
            }
        }
    }

    private static void loadImage(Context context, OnBackgroundChangeListener activity, String id, File file) {
        Log.e("lzs", "loadImage" + System.currentTimeMillis());
        //保存聊天id
        PreferenceUtils.putString(context, id, file.getAbsolutePath());

        //图片文件存在
        Glide.with(context).load(file).into(new SimpleTarget<GlideDrawable>(ScreenUtil.getScreenWidth(context), ScreenUtil.getScreenHeight(context)) {
            @Override
            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                Log.e("lzs", "onResourceReady" + System.currentTimeMillis());
                if (activity != null) {
                    activity.handle(false, resource);
                }
            }
        });
    }

//    public static void setTransparent(ViewGroup rootViewGroup) {
//        for (int i = 0; i < rootViewGroup.getChildCount(); i++) {
//            View view = rootViewGroup.getChildAt(i);
//            if (view instanceof ViewGroup) {
//                setTransparent((ViewGroup) view);
//                Drawable drawable = view.getBackground();
//                if (drawable != null && drawable instanceof ColorDrawable && drawable.isVisible()) {
//                    view.setBackgroundColor(Color.TRANSPARENT);
//                }
//            }
//        }
//    }

    public static void resetBackground(ViewGroup rootViewGroup) {
//        rootViewGroup.setBackground(null);
//        for (int i = 0; i < rootViewGroup.getChildCount(); i++) {
//            View view = rootViewGroup.getChildAt(i);
//            if (view instanceof ViewGroup) {
//                resetBackground((ViewGroup) view);
//                if (view.getId() == R.id.mergerStatus) {
//                    Log.e("lzs", "重置背景");
//                    view.setBackgroundColor(Color.WHITE);
//                }
//                if (view.getId() == R.id.chat_bottom_view) {
//                    view.setBackgroundColor(Color.WHITE);
//                }
//                if (view.getId() == R.id.rl_chat_list) {
//                    view.setBackgroundColor(view.getContext().getResources().getColor(R.color.Grey_100));
//                }
//            }
//        }
    }


    public static void useBackgroud(Context context, String user_id, String imageID) {
        Boolean flag = PreferenceUtils.getBoolean(context, perfix + user_id + imageID);
        if (flag == null || !flag) {
            //没有回调过使用次数,发起回调
            downloadCallBack(imageID, user_id, context);
        }
    }

    /**
     * 使用背景图回调使用
     */
    private static void downloadCallBack(String imageID, String user_id, Context context) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", CoreManager.getSelfStatus(context).accessToken);
        params.put("id", imageID);
        params.put("numbserUsers", "1");
        HttpUtils.get().url(CoreManager.getConfig(context).CHAT_BACKGROUND_LIST_DOWNLOAD_CALLBACK)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {


                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        //回调成功
                        //Log.e("lzs", "使用背景图回调成功 imageID:" + imageID);

                        PreferenceUtils.putBoolean(context, perfix + user_id + imageID, true);
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }

    public interface OnBackgroundChangeListener extends LifecycleOwner {
        /**
         * @param isReset  true 恢复默认设置 drawable =null  false:设置新的背景图
         * @param drawable
         */
        void handle(boolean isReset, Drawable drawable);
    }


}
